<template>
  <div class="app-container">
    <el-col :span="24" class="title-row">
      <span>| 修改绿地范围</span>
    </el-col>
    <el-form
      id="elForm"
      ref="elForm"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="110px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="OBJECTID" prop="objectid">
            <el-input
              v-model="formData.objectid"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入名称"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="绿地大类" prop="category_type">
            <el-select
              v-model="formData.category_type"
              placeholder="请选择绿地大类"
              :disabled="true"
              clearable
              @change="handleChangeType"
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in typeOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="绿地中类" prop="medium_type">
            <el-select
              v-model="formData.medium_type"
              placeholder="请选择绿地中类"
              :disabled="true"
              clearable
              @change="handleChangeTypem"
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in typemOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供水模式" prop="water_supply">
            <el-select
              v-model="formData.water_supply"
              placeholder="请选择供水模式"
              :disabled="true"
              multiple
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in dict.type.sys_guangms"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供水水源" prop="water_source">
            <el-select
              v-model="formData.water_source"
              placeholder="请选择供水水源"
              :disabled="true"
              multiple
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in dict.type.sys_guangsy"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入地址"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="与三调数据对比" prop="sjly">
            <el-input
              v-model="formData.sjly"
              placeholder="请输入与三调对比结果"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="信息记录备注" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入信息记录备注"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="false">
          <el-form-item label="上传照片" prop="field130">
            <!-- <el-upload
              ref="field130"
              auto-upload="false"
              :file-list="field130fileList"
              action="#"
              :before-upload="field130BeforeUpload"
              name="attachment"
            >
              <el-button size="small" type="primary" icon="el-icon-upload"
                >点击上传</el-button
              >
            </el-upload> -->
            <el-upload
              action="#"
              :auto-upload="false"
              list-type="text"
              :on-preview="handlePictureCardPreview"
              :file-list="picFileList"
              :on-remove="handleRemove"
              :on-change="handleChange"
              name="attachment"
              :multiple="true"
              :limit="3"
              :on-exceed="handleExceed"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" v-dialogDrags width="50%">
              <img
                width="100%"
                :src="dialogImageUrl"
                alt=""
                :preview-src-list="picFileList"
              />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="footer">
        <el-button type="primary" @click="submitForm" icon="el-icon-check"
          >提交</el-button
        >
        <!-- <el-button
        type="danger"
        plain
        icon="el-icon-edit"
        size="mini"
        :disabled="multiple"
        @click="handleeditgeo()"
        v-hasPermi="['datamanage:region:editgeo']"
        >修改几何</el-button
      > -->
        <!-- <el-button @click="resetForm">重置</el-button> -->
        <el-button
          type="primary"
          plain
          icon="el-icon-circle-close"
          @click="cancel"
          >返回</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Sketch from "@arcgis/core/widgets/Sketch";
import { mapActions, mapGetters } from "vuex";
import {
  addAttach,
  getAttachList,
  deleteAttach,
} from "../../../api/attachment/attach";
export default {
  props: {
    paramObj: { default: () => {} },
    mapview: { default: () => {} },
  },
  inject: ["toggleComponent"],
  dicts: [
    "sys_greenland_type",
    "sys_greenland_type_m",
    "sys_guangms",
    "sys_guangsy",
  ],
  data() {
    return {
      picFileList: [],
      formData: {},
      rules: {
        objectid: [],
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
        category_type: [
          {
            required: true,
            message: "请选择一个绿地大类",
            trigger: "change",
          },
        ],
        medium_type: [
          {
            required: false,
            message: "请选择一个绿地中类",
            trigger: "change",
          },
        ],
        water_supply: [
          {
            required: true,
            message: "请选择供水方式",
            trigger: "change",
          },
        ],
        water_source: [
          {
            required: true,
            message: "请选择供水水源",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入地址",
            trigger: "blur",
          },
        ],
        remark: [
          {
            // required: true,
            message: "请输入信息记录备注",
            trigger: "blur",
          },
        ],
        sjly: [
          {
            // required: true,
            message: "请输入与三调数据对比结果",
            trigger: "blur",
          },
        ],
      },
      feature: undefined,
      featureLayer: undefined,
      layerView: undefined,
      selectedGraphic: undefined,
      udpateGraphicsLayer: undefined,
      dialogImageUrl: "",
      dialogVisible: false,
      deleteAttachmentIds: [],
      addAttachments: [],
      sketch: undefined,
      // 所属街道
      suosjdOptions: [],
      // 所属社区
      suossqOptions: [],
      // 绿地大类
      typeOptions: [],
      // 绿地中类
      typemOptions: [],
      // 绿地小类
      typesOptions: [],
      // 草图微件添加的图形
      addGraphics: [],
    };
  },
  activated() {
    let _self = this;
    // 移除前一个高亮图形
    _self.removeHighlight("roadld_highlight");
    _self.feature = this.paramObj.feature;
    this.feature.attributes.water_supply =
      this.feature.attributes.water_supply?.split(",");
    this.feature.attributes.water_source =
      this.feature.attributes.water_source?.split(",");
    _self.formData = this.feature.attributes;
    _self.featureLayer = this.paramObj.featureLayer;
    _self.layerView = this.paramObj.layerView;
    _self.deleteAttachmentIds = [];
    _self.addAttachments = [];
    _self.initSelectOptions();
    // 查询附件
    _self.getAttachment();
    // 显示图形编辑面板
    // _self.updateGeometry();
    // 几何编辑微件
  },
  computed: { ...mapGetters(["nickName", "deptId"]) },
  deactivated() {
    this.clearGraphics();
  },
  created() {},
  mounted() {},
  methods: {
    ...mapActions("map", ["setHighlight", "removeHighlight", "cleanHighlight"]),
    // 初始化下拉列表
    initSelectOptions() {
      let _self = this;
      // axios.get("/config/city.json").then((res) => {
      //   _self.suosjdOptions = res.data;
      // });
      _self.suosjdOptions = city;
      // axios.get("/config/types.json").then((res) => {
      //   _self.typeOptions = res.data;
      _self.typeOptions = types;
      const filterTypeOptions = _self.typeOptions.filter(
        (item) => item.value == _self.feature.attributes.category_type
      );
      if (
        filterTypeOptions.length != 0 &&
        filterTypeOptions[0].children != null
      )
        _self.typemOptions = filterTypeOptions[0].children;
      const filterTypemOptions = _self.typemOptions.filter(
        (item) => item.value == _self.feature.attributes.medium_type
      );
      if (
        filterTypemOptions.length != 0 &&
        filterTypemOptions[0].children != null
      )
        _self.typesOptions = filterTypemOptions[0].children;
      // });
    },
    // 查询附件
    getAttachment() {
      let _self = this;
      _self.picFileList = [];
      const attachGroupId = _self.formData.photo;
      if (attachGroupId == undefined) return;
      getAttachList(attachGroupId).then((response) => {
        if (response.code == "200" && response.data) {
          response.data.rows.forEach((element) => {
            const prefixUrl = window.mapConfig.nodeurl + "/attachfiles/";

            var obj = {
              id: element.attachId,
              name: element.attachName,
              url: prefixUrl + element.attachId + "." + element.attachType,
            };
            _self.picFileList.push(obj);
          });
        }
      });
    },
    // 获取要删除的附件id
    handleRemove(file) {
      console.log(file);
      // 如果是附件列表里存在则添加到待删除附件列表里
      if (file.url != undefined && file.url.indexOf("attachfiles") > 0)
        this.deleteAttachmentIds.push(file.id);
      this.addAttachments = this.addAttachments.filter(
        (val) => val.uid !== file.uid
      );
    },

    // 获取
    handleChange(file) {
      this.addAttachments.push(file);
      console.log(this.addAttachments);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 街道选择
    handleChangeSuosjd(value) {
      this.suossqOptions = this.suosjdOptions.filter(
        (item) => item.value == value
      )[0].children;
    },
    // 绿地大类选择
    handleChangeType(value) {
      this.typemOptions = this.typeOptions.filter(
        (item) => item.value == value
      )[0].children;
    },
    // 绿地中类选择
    handleChangeTypem(value) {
      this.typesOptions = this.typemOptions.filter(
        (item) => item.value == value
      )[0].children;
    },

    submitForm() {
      let _self = this;
      _self.$refs["elForm"].validate((valid) => {
        if (!valid) return;
        // if (_self.selectedGraphic == undefined) {
        //   _self.$message.error("请添加空间位置信息后再提交！");
        //   return;
        // }
        // 设置更新后的位置
        // _self.feature.geometry =
        //   _self.selectedGraphic == undefined
        //     ? ""
        //     : _self.selectedGraphic.geometry;
        // console.log(_self.feature.geometry.toJSON());
        // 核查状态改为0
        _self.feature.attributes.hczt = 0;
        _self.feature.attributes.water_source =
          _self.feature.attributes.water_source?.toString();
        _self.feature.attributes.water_supply =
          _self.feature.attributes.water_supply?.toString();
        _self.feature.attributes.collecttime = Date.now();
        _self.feature.attributes.collector = _self.nickName;
        const edits = {
          updateFeatures: [_self.feature],
        };
        // 更新要素
        _self.featureLayer.applyEdits(edits).then(() => {
          _self.$message.success("修改成功");
          // 退出
          _self.cancel();
        });
      });
    },
    resetForm() {
      this.$refs["elForm"].resetFields();
      this.getAttachment();
      this.deleteAttachmentIds = [];
    },
    // 更新空间位置
    updateGeometry() {
      let _self = this;
      _self.udpateGraphicsLayer = new GraphicsLayer();
      _self.mapview.map.add(_self.udpateGraphicsLayer);
      _self.sketch = new Sketch({
        layer: _self.udpateGraphicsLayer,
        view: _self.mapview,
        // graphic will be selected as soon as it is created
        creationMode: "update",
      });
      // 设置绘图工具条显示要素
      _self.sketch.visibleElements = {
        createTools: {
          point: false,
          polyline: false,
          polygon: true,
          rectangle: false,
          circle: false,
        },
        selectionTools: {
          "lasso-selection": false,
          "rectangle-selection": false,
        },
        settingsMenu: false,
      };
      // 指定要更新的图形
      _self.selectedGraphic = new Graphic({
        geometry: _self.feature.geometry,
        symbol: window.mapConfig.symbols.polygonLocate,
      });
      _self.udpateGraphicsLayer.add(_self.selectedGraphic);
      _self.sketch.update(_self.selectedGraphic);
      _self.mapview.ui.add(_self.sketch, "top-right");
      _self.sketch.when(() => {
        // 初始时先隐藏创建图形按钮
        // 每个要素只有一个面，如果已创建的一个面，则不允许继续创建面。隐藏创建点按钮
        document.getElementsByClassName(
          "esri-sketch__section esri-sketch__tool-section"
        )[1].style.display = "none";
      });

      _self.sketch.on("create", (event) => {
        if (event.state === "complete") {
          console.log("create complete");
          _self.selectedGraphic = event.graphic;
          _self.addGraphics.push(event.graphic);
          // 每个要素只有一个面，如果已创建的一个面，则不允许继续创建面。隐藏创建点按钮
          if (_self.addGraphics.length > 0)
            document.getElementsByClassName(
              "esri-sketch__section esri-sketch__tool-section"
            )[1].style.display = "none";
          // _self.mapview.graphics.add(event.graphic);
          // _self.mapview.ui.remove(_self.sketch);
        }
      });

      _self.sketch.on("update", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          // _self.udpateGraphicsLayer.add(event.graphics);
        }
      });
      _self.sketch.on("delete", (event) => {
        _self.layerView.filter = {
          where: `objectid<>${_self.feature.attributes.objectid}`,
        };
        _self.udpateGraphicsLayer.remove(event.graphics);
        event.graphics.forEach((graphic) => {
          console.log("deleted", graphic);
          if (graphic == _self.selectedGraphic)
            _self.selectedGraphic = undefined;
          _self.addGraphics = _self.addGraphics.filter(
            (item) => item !== graphic
          );
        });
        // 如果没有添加任何面，就显示创建面按钮
        if (_self.addGraphics.length == 0)
          document.getElementsByClassName(
            "esri-sketch__section esri-sketch__tool-section"
          )[1].style.display = "";
      });
    },
    clearGraphics() {
      let _self = this;
      // 清空新增的图形
      _self.addGraphics = [];
      // 删除编辑微件
      _self.mapview.ui.remove(_self.sketch);
      // 移除编辑图层
      _self.mapview.map.layers.remove(_self.udpateGraphicsLayer);
    },
    cancel() {
      let _self = this;
      _self.clearGraphics();
      _self.layerView.filter = null;
      this.removeHighlight("roadld_highlight");
      // 切换至数据列表界面
      this.toggleComponent("dataPanel");
    },
  },
};
</script>

<style lang="scss" scoped>
.title-row {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  color: #11a983;
  margin-bottom: 1vh;
}
.header {
  display: flex;
  justify-content: space-between;
}
.footer {
  margin-bottom: 1vh;
  display: flex;
  justify-content: center;
}
::v-deep .el-dialog__header {
  padding: 40px 20px 10px;
}
#domCart1 {
  width: 100%;
  height: 100%;
}
.el-upload__tip {
  line-height: 1.2;
}
::v-deep .el-form-item {
  margin-bottom: 20px;
}
</style>

<!-- [{
    "statisticType": "count",
    "onStatisticField": "OBJECTID",
    "outStatisticFieldName": "Count"
}] -->
